package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.BaiduMapUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author lwd
 * @since 2023-04-24
 */
@Slf4j
@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;


    @Value("${sky.baidu.shopAddress}")
    private String shopAddress;
    @Value("${sky.baidu.ak}")
    private String ak;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //0、校验地址是否存在、校验购物车是否为空
        final AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (ObjectUtils.isEmpty(addressBook)) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        Long userId = BaseContext.getCurrentId();
        ShoppingCart params = ShoppingCart.builder().userId(userId).build();
        final List<ShoppingCart> cartList = shoppingCartMapper.queryByParmas(params);
        if (ObjectUtils.isEmpty(cartList)) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //0.1校验地址是否超出范围
        //TODO 可以调用httpclit工具类
        final String destinationAddres = addressBook.getProvinceName() + addressBook.getCityName()
                + addressBook.getDistrictName() + addressBook.getDetail();
        int dist = 0;
        try {
            Map<String, String> originlngAndLat = new HashMap<>();
            Map<String, String> destinationAndLat = new HashMap<>();
            originlngAndLat = BaiduMapUtil.getLngAndLat(shopAddress, ak);
            destinationAndLat = BaiduMapUtil.getLngAndLat(destinationAddres, ak);
            String massenge = BaiduMapUtil.getRouteMassenge(originlngAndLat, destinationAndLat, ak);
            org.codehaus.jettison.json.JSONObject jsonObject = new org.codehaus.jettison.json.JSONObject(massenge);
            String distance = jsonObject.getJSONObject("result").getJSONArray("routes").getJSONObject(0).getString("distance");
            System.out.println(jsonObject.getJSONObject("result").getJSONArray("routes").getJSONObject(0));
            dist = Integer.parseInt(distance);
            System.out.println("配送距离为：" + dist);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (dist > 5000) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_DISPOSITION_MAX);
        }

        //1、组装Orders，保存至Orders表
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setNumber(Long.valueOf(System.currentTimeMillis()).toString());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setUserName(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());

        this.ordersMapper.save(orders);

        //2、根据购物车，组装OrderDetails List，保存至OrderDetail表（N条数据）
        List<OrderDetail> orderDetails = new ArrayList<>();
        cartList.forEach(cart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        });
        this.orderDetailMapper.batchSave(orderDetails);

        //3、清空购物车
        this.shoppingCartMapper.clean(userId);

        //4、组装OrderSubmitVO并返回
        final OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder().id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    @Override
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
        //支付成功后，给后台发送来单提醒
        Map map =new HashMap();
        map.put("type",1);//1代表来单提醒，2代表催单
        map.put("orderId",orders.getId());
        map.put("content","订单号:"+orders.getNumber());
        String msg = JSON.toJSONString(map);//转化为json格式发送给前端
        webSocketServer.sendToAllClient(msg);
    }

    /**
     * 管理端订单搜索
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 设置分页参数
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        // 根据条件查询订单
        List<OrderVO> orderVOList = ordersMapper.getByCondition(ordersPageQueryDTO);
        // 分页查询
        Page<OrderVO> page = (Page<OrderVO>) orderVOList;

        // 处理回传数据（设置菜品信息）
        List<OrderVO> result = page.getResult();

        result.forEach(r -> {
            // 查询订单详情
            List<OrderDetail> orderDetailList = r.getOrderDetailList();
            List<String> orderDishList = orderDetailList.stream().map(o -> {
                // 设置菜品信息的格式为（菜品名称*数量）
                String orderDish = o.getName() + "*" + o.getNumber() + ";";
                return orderDish;
            }).collect(Collectors.toList());
            String join = String.join("", orderDishList);
            r.setOrderDishes(join);
        });

        return new PageResult(page.getTotal(), result);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //根据id查询订单
        Orders ordersRejection = ordersMapper.getById(ordersRejectionDTO.getId());
        //状态为2待接单则不能拒单
        if (ObjectUtils.isEmpty(ordersRejection.getStatus().equals(Orders.TO_BE_CONFIRMED))) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = Orders.builder()
                .id(ordersRejection.getId())
                .status(Orders.CANCELLED)
                .rejectionReason(ordersRejection.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .build();
        //3.查询订单支付状态如果是已支付则需退款
        if (orders.getPayStatus() == Orders.PAID) {
            //调用微信接口退款
            try {
                String refund = weChatPayUtil.refund(
                        orders.getNumber(),
                        orders.getNumber(),
                        new BigDecimal(0.01),
                        new BigDecimal(0.01));
                log.info("取消订单退款：{}", refund);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //退款成功修改支付状态
            orders.setPayStatus(Orders.REFUND);
        }

        ordersMapper.update(orders);

    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        //1.根据id查询订单
        Orders byId = ordersMapper.getById(ordersCancelDTO.getId());
        //2.组装order
        Orders order = Orders.builder()
                .id(byId.getId())
                .status(Orders.CANCELLED)
                .rejectionReason(byId.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .build();
        //3.查询订单支付状态如果是已支付则需退款
        if (byId.getPayStatus() == Orders.PAID) {
            //调用微信接口退款
            try {
                String refund = weChatPayUtil.refund(
                        byId.getNumber(),
                        byId.getNumber(),
                        new BigDecimal(0.01),
                        new BigDecimal(0.01));
                log.info("取消订单退款：{}", refund);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //退款成功修改支付状态
            order.setPayStatus(Orders.REFUND);
        }
        //3.修改订单状态
        ordersMapper.update(order);
    }

    /**
     * 各个状态的订单数量统计
     */
    @Override
    public OrderStatisticsVO numOfAllOrdersStatus() {
        Orders orders = new Orders();
        //查询待接单数量
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        Integer num1 = ordersMapper.numOfToBeConfirmed(orders);
        //待派送数量
        orders.setStatus(Orders.CONFIRMED);
        Integer num2 = ordersMapper.numOfConfirmed(orders);
        //派送中数量
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        Integer num3 = ordersMapper.numOfDeliveryInProgress(orders);
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(num1);
        orderStatisticsVO.setConfirmed(num2);
        orderStatisticsVO.setDeliveryInProgress(num3);
        return orderStatisticsVO;
    }

    /**
     * 历史订单查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        //开启分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //查询订单
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        Page<OrderVO> page = ordersMapper.historyOrders(ordersPageQueryDTO);
        //提取属性，封装
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO getDetailById(Long id) {
        //查询订单信息
        Orders order = ordersMapper.getById(id);
        //转json
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        // 查询订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;

    }

    /**
     * 接单
     *
     * @param ordersDTO
     */
    @Override
    public void confirmById(OrdersDTO ordersDTO) {
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersDTO, order);
        order.setStatus(Orders.CONFIRMED);
        ordersMapper.update(order);
    }

    /**
     * 订单派送
     *
     * @param id
     */
    @Override
    public void deliveryById(Long id) {
        //判断订单的状态
        Orders order = ordersMapper.getById(id);
        if (order.getStatus() != Orders.CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //修改订单状态
        order.setId(id);
        order.setStatus(Orders.DELIVERY_IN_PROGRESS);
        ordersMapper.update(order);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void completeById(Long id) {
        //判断订单状态
        Orders order = ordersMapper.getById(id);
        if (order.getStatus() == null || order.getStatus() != Orders.DELIVERY_IN_PROGRESS) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //修改订单状态
        order.setId(id);
        order.setStatus(Orders.COMPLETED);
        order.setDeliveryTime(LocalDateTime.now());
        this.ordersMapper.update(order);
    }

    /**
     * 用户取消订单
     */
    @Override
    public void cancel(Long id) throws Exception {
        //1.根据id查询订单
        Orders orders = ordersMapper.getCancelById(id);
        //2.判断订单是否存在
        if (ObjectUtils.isEmpty(orders)) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //3.判断订单状态是否为已支付状态
        if (orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders1 = new Orders();
        //把订单id赋给创建的对象
        orders1.setId(orders.getId());
        if (orders.getStatus().equals(orders1.TO_BE_CONFIRMED)) {
            //4，如果为已支付，则退款并取消订单
            weChatPayUtil.refund(
                    orders.getNumber(),//商户订单号
                    orders.getNumber(),//商户退款订单号
                    orders.getAmount(),//实收金额
                    orders.getAmount()//退款金额
            );
            orders1.setPayStatus(Orders.REFUND);//修改订单的支付状态
        }
        //5.修改订单的信息
        orders1.setStatus(Orders.CANCELLED);
        orders1.setCancelReason("取消订单");
        orders1.setCancelTime(LocalDateTime.now());
        ordersMapper.update(orders1);
    }
    /**
     * 用户催单
     */
    @Override
    public void reminder(Long id) {
        //查看订单是否存在
        Orders orders =ordersMapper.getById(id);
        if (orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //用户点击催单后，给前台发送催单信息
        Map map =new HashMap();
        map.put("type",2);//1代表来单提醒，2代表催单
        map.put("orderId",id);
        map.put("content","订单号:"+orders.getNumber());
        String msg = JSON.toJSONString(map);//转化为json格式发送给前端
        webSocketServer.sendToAllClient(msg);
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        // 根据id获取订单的订单详情数据
        List<OrderDetail> orderDetailList = orderDetailMapper.getOrderDetail(id);
        // 将订单详情转存到购物车
        List<ShoppingCart> shoppingCarts = new ArrayList<>();
        orderDetailList.forEach(o -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(o, shoppingCart, "id");
            // 封装购物车对象
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            // 将购物车对象添加进集合
            shoppingCarts.add(shoppingCart);
        });
        // 添加购物车
        shoppingCartMapper.saveBatch(shoppingCarts);
    }


}
